let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
let img = new Image();
let width = canvas.width;
let height = canvas.height;
let imgWidth = 200,
  imgHeight = 100,
  imgX = (width - imgWidth) / 2,
  imgY = (height - imgHeight) / 2,
  mousedownX = 0,
  mousedownY = 0;
let zoom = 1.1; // 缩放倍数

img.src = "timg.jpg"
img.onload = function () {
  drawImg()
};

canvas.onmousewheel = function (e) {
  if (e.wheelDelta > 0) {
    imgWidth = imgWidth * zoom;
    imgHeight = imgHeight * zoom;
  } else {
    imgWidth = imgWidth / zoom;
    imgHeight = imgHeight / zoom;
  }

  imgX /= zoom;
  imgY /= zoom;

  // imgX = (width - imgWidth) / 2
  // imgY = (height - imgHeight) / 2
  drawImg();
}

canvas.onmousedown = function (e) {
  console.log(e.offsetX)
  let movingX, movingY;
  mousedownX = e.offsetX
  mousedownY = e.offsetY

  canvas.onmousemove = function (e) {
    movingX = e.offsetX - mousedownX;
    movingY = e.offsetY - mousedownY;

    drawImg(imgX + movingX, imgY + movingY);
    // imgX += movingX;
    // imgY += movingY;
  };

  canvas.onmouseup = function (e) {
    canvas.onmousemove = function() {};
    imgX += movingX;
    imgY += movingY;
  };

  document.onmouseup = function (e) {
    if (e.target !== canvas) {
      canvas.onmousemove = function() {};
      imgX += movingX;
      imgY += movingY;
    }
  }
}

// 清除画布
function clear() {
  ctx.clearRect(0, 0, width, height);
}

// 绘制图片
function drawImg(x = imgX, y = imgY) {
  clear();
  ctx.drawImage(img, x, y, imgWidth, imgHeight);
}


